package org.aplombh.java.utils.multiThread.deathLock;

public class NoDeathLock extends Thread {

    public static void main(String[] args) {
        NoDeathLock cinderella = new NoDeathLock(0, "Cinderella");
        NoDeathLock snowWhite = new NoDeathLock(1, "Snow White");


        cinderella.start();
        snowWhite.start();
    }


    static final Mirror mirror = new Mirror();
    static final Lipstick lipstick = new Lipstick();

    int choice;
    String name;

    public NoDeathLock(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void makeup() throws InterruptedException {
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(this.name + " get lipstick;");
            }

            Thread.sleep(1000);
            System.out.println("One second," + this.name + " want to get mirror;");

            synchronized (mirror) {
                System.out.println(this.name + " get mirror;");
            }
        } else{
            synchronized (mirror) {
                System.out.println(this.name + " get mirror;");
            }

            Thread.sleep(1000);
            System.out.println("One second," + this.name + " want to get lipstick;");

            synchronized (lipstick) {
                System.out.println(this.name + " get lipstick;");
            }
        }
    }
}

